package ch.areion.areionapp.engine;

import java.nio.ByteBuffer;

/**
 * Enumeration of Motor Driver registers.
 * @author RetoMueller
 * @version 1.0
 */
public final class MotorDriver
{
	/**
	 * Speed correction factor. Max speed reachable is 1000 / factor  [m/s].
	 */
	public final static int SPEED_CORRECTION = 2;
	
	/**
	 * Time to wait after a IIC communication with the MotorDriver. [ms]
	 */
	public final static int WAIT_TIME = 10;
	
	/**
	 * All the Registers off the MotorDriver IIC-Interface.
	 */
	public enum Register
	{
		STATUS,
		CONTROL,
		M1_SPEED_HB,
		M1_SPEED_LB,
		M2_SPEED_HB,
		M2_SPEED_LB,
		MOT_TARGET_TICKS_HB,
		MOT_TARGET_TICKS_LB,
		M1_ENC_TICKS_HB,
		M1_ENC_TICKS_LB,
		M2_ENC_TICKS_HB,
		M2_ENC_TICKS_LB;


		/**
		 * Public address of the MotorDriver slave.
		 */
		public static final int SLAVE_ADR = 0x2A;

		/**
		 * Get byte array with the register command byte in it.
		 * @return byte[] address of register
		 */
		public byte[] cmd() {
			return new byte[]{(byte)this.ordinal()};
		}

		/**
		 * Get the register number as byte.
		 * @return byte address of register
		 */
		public byte byt() {
			return (byte)this.ordinal();
		}

		/**
		 * Converts a byte array to a short number.
		 * @param array byte array
		 * @param pos start position from the relevant bytes
		 * @return short value of the byte array
		 */
		public static final short toShort(byte[] array, int pos)
		{
			ByteBuffer bb = ByteBuffer.wrap(array, pos, 2);
			return bb.getShort();
			//return (short)((argB1 & 0xff) | (argB2 << 8));
		}
		
		/**
		 * Converts a short number to a byte array.
		 * @param array byte array
		 * @param pos start position from the relevant bytes
		 * @return short value of the byte array
		 */
		public static byte[] toBytes(short x){
			byte[] a = new byte[2];
			a[0] = (byte)(x & 0xff);        //LowByte
			a[1] = (byte)((x >> 8) & 0xff); //HighByte
			return a;
		}
	}
	
	/**
	 * Bits of the Status register.
	 */
	public enum Status
	{
		BUSY;
		

		/**
		 * Set the specific bit.
		 * @return register value if the one bit is set
		 */
		public final byte set() {
			return (byte)(1<<this.ordinal());
		}
	}

	/**
	 * Bits of the Control register.
	 */
	public enum Control
	{
		MOTOR_STOP,
		RESET_TICKS;
		

		/**
		 * Set the specific bit.
		 * @return register value if the one bit is set
		 */
		public final byte set() {
			return (byte)(1<<this.ordinal());
		}
	}
}
